import { ICreateMenu, IUpdateMenu } from "../types";
let metamenu: { cached: boolean, fetching: boolean, data: any[] } = { cached: false, fetching: false, data: [] }
import mitt from "mitt";
const emitter = mitt();
const event: Record<string, string> = {
    metamenuReady: "metamenuReady",
}

export function getAll(): Promise<any> {
    if (metamenu.cached) {
        return new Promise((resolve) => {
            resolve(metamenu.data);
        });
    }
    if (metamenu.fetching) {
        return new Promise((resolve) => {
            emitter.on(event.metamenuReady, () => {
                resolve(metamenu.data);
            })
            if(metamenu.cached){
                resolve(metamenu.data);
            }
        });
    }
    metamenu.fetching = true;
    const url = '/menu/all/get';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, {})
            .then((response: any) => {
                metamenu.data = response;
                metamenu.cached = true;
                metamenu.fetching = false;
                emitter.emit(event.metamenuReady);
                resolve(response);
            })
            .catch((err: any) => {
                metamenu.fetching = false;
                reject(err);
            });
    });
}

export function create(data: ICreateMenu): Promise<any> {
    const url = '/menu/save';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, data)
            .then((response: any) => {
                metamenu.cached = false;
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}

export function update(data: IUpdateMenu): Promise<any> {
    const url = '/menu/update';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, data)
            .then((response: any) => {
                metamenu.cached = false;
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}
export function remove(id: string | number): Promise<any> {
    const url = '/menu/delete';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, { id: id })
            .then((response: any) => {
                metamenu.cached = false;
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}
export function save(data: any): Promise<any> {
    if (data.id) {
        return update(data as IUpdateMenu);
    } else {
        return create(data as ICreateMenu);
    }
}